<template>
    <div class="flex flex-col grow-1">
        <v-banner single-line>
            <div class="flex items-center shrink-0">
                <el-radio-group v-model="searchForm.type" size="small">
                    <el-radio-button label="">全部</el-radio-button>
                    <el-radio-button :label="0">待办事项</el-radio-button>
                    <el-radio-button :label="1">开发需求</el-radio-button>
                    <el-radio-button :label="2">BUG修复</el-radio-button>
                    <el-radio-button :label="3">异常处理</el-radio-button>
                </el-radio-group>
                <el-radio-group class="ml-4" v-model="searchForm.status">
                    <el-radio label="">全部</el-radio>
                    <el-radio :label="0">新建</el-radio>
                    <el-radio :label="1">进行中</el-radio>
                    <el-radio :label="2">挂起</el-radio>
                    <el-radio :label="3">完成</el-radio>
                    <el-radio :label="4">删除</el-radio>
                </el-radio-group>
                <div @click="isSearchSelect = !isSearchSelect" style="width: 58px;"
                    :class="{ 'text-sky-700': isSearchSelect, 'border-sky-700': isSearchSelect, 'border-slate-300': !isSearchSelect, 'text-slate-300': !isSearchSelect }"
                    class="select-none ml-4 rounded-full border p-1 cursor-pointer text-xs">
                    <i class="el-icon-search"></i>
                    <span class="ml-1">搜索</span>
                </div>
                <div class="me-1 ms-auto">
                    <v-dialog v-model="releaseVisible" max-width="600px">
                        <template v-slot:activator="{ on, attrs }">
                            <v-btn @click="onReleaseTask" v-bind="attrs" v-on="on" v-show="searchForm.status === 3"
                                class="me-2" color="primary">
                                <span>发布</span>
                            </v-btn>
                        </template>
                        <v-card class="p-4">
                            <el-form v-if="releaseVisible" :model="releaseForm" ref="releaseFormComponent"
                                label-width="100px" label-position="left">
                                <el-form-item prop="description" label="备注" required>
                                    <el-input type="textarea" :rows="4" v-model="releaseForm.description"></el-input>
                                </el-form-item>

                                <el-form-item>
                                    <div class="text-right">
                                        <el-button :loading="releaseLoading" type="primary"
                                            @click="onReleaseTaskSubmit">提交</el-button>
                                    </div>
                                </el-form-item>
                            </el-form>
                        </v-card>
                    </v-dialog>
                    <v-dialog v-model="createVisible" max-width="600px">
                        <template v-slot:activator="{ on, attrs }">
                            <v-btn v-bind="attrs" v-on="on" color="primary">
                                <span>创建任务</span>
                            </v-btn>
                        </template>
                        <v-card class="p-4">
                            <el-form v-if="createVisible" :model="createForm" ref="createFormComponent"
                                label-width="100px" label-position="left">
                                <el-form-item prop="schema">
                                    <el-radio-group v-model="createForm.schema">
                                        <el-radio :label="0">未完成</el-radio>
                                        <el-radio :label="1">已完成</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item v-if="createForm.parentId" label="父任务">
                                    <el-input :disabled="true" v-model="createForm.parentTitle"></el-input>
                                </el-form-item>
                                <el-form-item prop="timeline" v-if="createForm.schema === 1" label="时间段">
                                    <el-date-picker v-model="createForm.timeline" type="datetimerange"
                                        :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期"
                                        end-placeholder="结束日期" align="right">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item prop="type" label="任务类型" required>
                                    <el-select v-model="createForm.type" placeholder="请选择">
                                        <el-option v-for="item in taskTypeOptions" :key="item.value" :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item prop="priority" label="优先级" required>
                                    <el-radio-group v-model="createForm.priority">
                                        <el-radio :label="1">1</el-radio>
                                        <el-radio :label="2">2</el-radio>
                                        <el-radio :label="3">3</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item prop="responsiblePeople" label="责任人" required>
                                    <el-select v-model="createForm.responsiblePeople" placeholder="请选择">
                                        <el-option v-for="item in responsiblePeopleOptions" :key="item.value"
                                            :label="item.label" :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>

                                <el-form-item prop="title" label="任务名" required>
                                    <el-input type="textarea" :rows="4" v-model="createForm.title"></el-input>
                                </el-form-item>
                                <!-- <el-form-item prop="assign" label="指派给">
                                <el-select v-model="createForm.assign" multiple placeholder="请选择">
                                    <el-option v-for="item in responsiblePeopleOptions" :key="item.value"
                                        :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item> -->

                                <el-form-item>
                                    <div class="text-right">
                                        <el-button type="primary" @click="onCreateSubmit">添加</el-button>
                                    </div>
                                </el-form-item>
                            </el-form>
                        </v-card>
                    </v-dialog>
                </div>

            </div>
        </v-banner>

        <div class="w-full p-3">
            <div style="height: 80px;" class="mb-2" v-if="isSearchSelect">
                <el-row :gutter="8">
                    <el-col class="flex items-center" :span="9">
                        <span class="shrink-0">任务名：</span>
                        <el-input v-model="searchForm.title" size="small"></el-input>
                    </el-col>
                    <el-col class="flex items-center" :span="5">
                        <span class="shrink-0">责任人：</span>
                        <el-select size="small" v-model="searchForm.responsiblePeople" placeholder="请选择">
                            <el-option v-for="item in responsiblePeopleOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col class="flex items-center" :span="5">
                        <span class="shrink-0">优先级：</span>
                        <el-select size="small" v-model="searchForm.priority" placeholder="请选择">
                            <el-option v-for="item in priorityOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col class="flex items-center" :span="5">
                        <span class="shrink-0">发布状态：</span>
                        <el-select size="small" v-model="searchForm.releaseFlag" placeholder="请选择">
                            <el-option v-for="item in releaseFlagOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col class="flex items-center mt-2" :span="5">
                        <span class="shrink-0">查询层级：</span>
                        <el-select size="small" v-model="searchForm.rootFlag" placeholder="请选择">
                            <el-option v-for="item in rootFlagOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col class="flex items-center mt-2 justify-center" :span="19">
                        <el-button :loading="fetchLoading" @click="onSearch" size="small" type="primary">搜索</el-button>
                        <el-button @click="onReset" size="small">重置</el-button>
                    </el-col>
                </el-row>
            </div>
            <el-table ref="elTable" v-loading="fetchLoading" @sort-change="onSortChange" border
                :height="isSearchSelect ? 'calc(100vh - 336px)' : 'calc(100vh - 248px)'"
                :cell-style="{ padding: '6px' }" :header-cell-style="{ padding: '6px' }" :data="tableData"
                style="width: 100%" :tree-props="{ children: 'children', hasChildren: 'childNum' }" lazy
                :load="loadChildren" row-key="id">
                <el-table-column v-if="searchForm.status === 3" fixed="left" sortable="custom" width="55"
                    type="selection">
                </el-table-column>

                <el-table-column fixed="left" min-width="400" show-overflow-tooltip prop="title" label="任务名">
                    <template slot-scope="scope">
                        <span class="t-link" @click="onNavTo(scope.row)">{{ scope.row.title }}</span>
                    </template>
                </el-table-column>
                <el-table-column fixed="left" sortable="custom" prop="priority" label="P" width="70" align="center">
                    <template slot-scope="scope">
                        <CircleNum :color="priorityColor(scope.row.priority)" :num="scope.row.priority" />
                    </template>
                </el-table-column>

                <!-- <el-table-column show-overflow-tooltip label="指派给" prop="assignNicknameListStr"
                    width="140"></el-table-column> -->

                <el-table-column prop="statusName" label="任务状态" width="120" align="center">
                    <template slot-scope="scope">
                        <div>
                            <span v-if="scope.row.status === 3" style="color: #67C23A">{{ scope.row.statusName }}</span>
                            <span v-else-if="scope.row.status === 2" style="color: #E6A23C">{{ scope.row.statusName
                            }}</span>
                            <span v-else-if="scope.row.status === 1" style="color: #409EFF">{{ scope.row.statusName
                            }}</span>
                            <span v-else>{{ scope.row.statusName }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="完成/全部" width="120" align="center">
                    <template slot-scope="scope">
                        <div>
                            <span>{{ scope.row.completeTodoNum }}</span>
                            <span>/</span>
                            <span>{{ scope.row.totalTodoNum }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="workMillisecond" label="工时(Hours)" width="120" align="center"></el-table-column>
                <el-table-column prop="responsiblePeopleName" label="责任人" width="120" align="center"></el-table-column>
                <el-table-column prop="typeName" label="任务类型" width="120" align="center"></el-table-column>
                <el-table-column prop="releaseFlagName" label="发布状态" width="120" align="center"></el-table-column>
                <el-table-column fixed="right" label="操作" width="320">
                    <template slot-scope="scope">
                        <div>
                            <el-button style="padding: 0 !important;" :loading="startLoading"
                                @click.native="onStartTask(scope.row)" :disabled="[1, 3, 4].includes(scope.row.status)"
                                type="text" icon="el-icon-video-play">开始</el-button>
                            <el-button style="padding: 0 !important;" :loading="pendingLoading"
                                :style="{ color: [1].includes(scope.row.status) ? '#E6A23C' : '' }"
                                @click.native="onPendingTask(scope.row)"
                                :disabled="[0, 2, 3, 4].includes(scope.row.status)" class="ml-2" type="text"
                                icon="el-icon-video-pause">挂起</el-button>
                            <el-button style="padding: 0 !important" @click="onEdit(scope.row)"
                                :disabled="!scope.row.isEdit" class="ml-2" type="text"
                                icon="el-icon-edit">编辑</el-button>
                            <el-button style="padding: 0 !important" @click="onCreateSub(scope.row)"
                                v-if="!scope.row.parentId" class="ml-2" type="text"
                                icon="el-icon-document-add">子项</el-button>
                            <el-popconfirm @confirm="onDeleteTask(scope.row)" title="是否确认删除">
                                <el-button :style="{ color: [0, 1, 2, 3].includes(scope.row.status) ? '#F56C6C' : '' }"
                                    style="padding: 0 !important" slot="reference" :loading="deleteLoading"
                                    :disabled="[4].includes(scope.row.status)" class="ml-2" type="text"
                                    icon="el-icon-delete">删除</el-button>
                            </el-popconfirm>

                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <v-dialog v-model="editVisible" max-width="600px">
                <v-card class="p-4">
                    <el-form :model="editForm" ref="editFormComponent" label-width="100px" label-position="left">
                        <el-form-item prop="priority" label="优先级" required>
                            <el-radio-group v-model="editForm.priority">
                                <el-radio :label="1">1</el-radio>
                                <el-radio :label="2">2</el-radio>
                                <el-radio :label="3">3</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item prop="responsiblePeople" label="责任人" required>
                            <el-select v-model="editForm.responsiblePeople" placeholder="请选择">
                                <el-option v-for="item in responsiblePeopleOptions" :key="item.value"
                                    :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="title" label="任务名" required>
                            <el-input type="textarea" :rows="4" v-model="editForm.title"></el-input>
                        </el-form-item>
                        <!-- <el-form-item prop="assign" label="指派给">
                            <el-select style="width: 260px" v-model="editForm.assign" multiple placeholder="请选择">
                                <el-option v-for="item in responsiblePeopleOptions" :key="item.value"
                                    :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item> -->

                        <el-form-item>
                            <div class="text-right">
                                <el-button type="primary" @click="onEditSubmit">修改</el-button>
                            </div>
                        </el-form-item>
                    </el-form>
                </v-card>
            </v-dialog>
            <el-pagination :current-page.sync="searchPageQuery.page" :page-sizes="[20, 60, 100]"
                :page-size.sync="searchPageQuery.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="searchTotal">
            </el-pagination>
        </div>
    </div>
</template>

<script>
import { defineComponent, ref, reactive, watch, toRef, nextTick } from '@vue/composition-api';
import CircleNum from '@/components/CircleNum/index.vue'
import router from '../../../../router';
import { getTaskList, createTask, getResponsiblePeopleList, editTask, startTask, pendingTask, deleteTask, releaseTask, createCompleteTask } from "@/api/task";
import { useUserStore } from '../../../../store/user';
import moment from 'moment';
export default defineComponent({
    components: {
        CircleNum
    },
    props: {
        orgId: Number
    },
    setup(props, { emit }) {
        const userStore = useUserStore()
        function priorityColor(priority) {
            if (priority === 1) {
                return '#F56C6C'
            } else if (priority === 2) {
                return '#E6A23C'
            } else if (priority === 3) {
                return '#409EFF'
            } else if (priority === 4) {
                return '#67C23A'
            }
        }
        const taskTypeOptions = reactive([
            { label: '待办事项', value: 0 },
            { label: '开发需求', value: 1 },
            { label: '修复BUG', value: 2 },
            { label: '异常处理', value: 3 }
        ])
        const priorityOptions = reactive([
            { label: '1', value: 1 },
            { label: '2', value: 2 },
            { label: '3', value: 3 }
        ])
        const releaseFlagOptions = reactive([
            { label: '全部', value: '' },
            { label: '待发布', value: 'N' },
            { label: '已发布', value: 'Y' },
        ])
        const rootFlagOptions = reactive([
            { label: '全部', value: '' },
            { label: 'ROOT', value: 'Y' },
        ])
        const responsiblePeopleOptions = ref([])
        const elTable = ref(null)
        const tableData = ref([]);
        const isSearchSelect = ref(false)
        const searchTotal = ref(0)
        const initSearchForm = {
            type: '',
            status: 0,
            title: '',
            priority: '',
            responsiblePeople: userStore.user.username,
            priorityOrder: null,
            releaseFlag: 'N',
            rootFlag: ''
        }
        const searchForm = reactive({
            type: '',
            status: 0,
            title: '',
            priority: '',
            responsiblePeople: userStore.user.username,
            priorityOrder: null,
            releaseFlag: 'N',
            rootFlag: ''
        })
        const searchPageQuery = reactive({
            page: 1,
            pageSize: 20,
        })
        watch(searchPageQuery, () => {
            fetchList()
        }, { deep: true })
        watch(toRef(searchForm, 'status'), () => {
            fetchList()
        })
        watch(toRef(searchForm, 'type'), () => {
            fetchList()
        })
        const fetchLoading = ref(false)
        function fetchList() {
            fetchLoading.value = true
            return getTaskList({
                orgId: props.orgId,
                ...searchForm,
                ...searchPageQuery,
            }).then((res) => {
                const data = res.data;
                tableData.value = []
                nextTick(() => {
                    tableData.value = data.list.map(item => ({
                        ...item,
                        workMillisecond: (item.workMillisecond / (1000 * 60 * 60)).toFixed(2),
                        childNum: !!item.childNum,
                        children: []
                        // assignNicknameListStr: item.assignNicknameList.join(',')
                    }))
                    searchTotal.value = data.total
                    nextTick(() => {
                        nextTick(() => {
                            elTable.value.doLayout();
                        })
                    })
                })
            }).finally(() => {
                fetchLoading.value = false
            })
        }
        function onSearch() {
            searchPageQuery.page = 1
            fetchList()
        }

        function onReset() {
            Object.keys(searchForm).forEach(key => {
                searchForm[key] = initSearchForm[key]
            })
            onSearch()
        }
        // ascending descending
        function onSortChange({ column, prop, order }) {
            console.log(column, prop, order)
            if (prop === 'priority') {
                searchForm.priorityOrder = order
            }
            fetchList()
        }

        function fetchResponsiblePeopleList() {
            getResponsiblePeopleList({})
                .then(res => {
                    const data = res.data
                    responsiblePeopleOptions.value = data
                })
        }
        fetchResponsiblePeopleList()
        watch(toRef(props, 'orgId'), (val) => {
            if (val) {
                fetchList()
            }
        }, { immediate: true })

        const createVisible = ref(false)

        const createForm = reactive({
            schema: 0,
            timeline: [],
            parentId: null,
            parentTitle: null,
            title: "",
            type: 0,
            priority: 2,
            responsiblePeople: userStore.user.username,
            assign: []
        });

        watch(createVisible, (val) => {
            if (!val) {
                createFormComponent.value.resetFields()
                createForm.parentId = null
                createForm.parentTitle = null
            }
        }, {
            flush: 'pre'
        })

        const createFormComponent = ref(null)
        function onCreateSubmit() {
            createFormComponent.value.validate((valid) => {
                if (valid) {
                    let createFun = async () => {}
                    if (createForm.schema === 0) {
                        createFun = createTask
                    } else if (createForm.schema === 1) {
                        createFun = createCompleteTask
                    }
                    createFun({
                        orgId: props.orgId,
                        ...createForm
                    }).then(() => {
                        fetchList()
                    }).finally(() => {
                        createVisible.value = false
                    })
                }
            })

        }

        function onCreateSub(row) {
            createForm.parentId = row.id
            createForm.parentTitle = row.title
            createVisible.value = true
        }

        const editVisible = ref(false)
        const editForm = reactive({
            id: null,
            title: "",
            priority: 2,
            responsiblePeople: '',
            assign: []
        });

        const editFormComponent = ref(null)
        function onEdit(row) {
            editForm.id = row.id
            editForm.title = row.title
            editForm.priority = row.priority
            editForm.responsiblePeople = row.responsiblePeople
            editForm.assign = []
            nextTick(() => {
                editVisible.value = true
            })
            setTimeout(() => {
                editForm.assign = row.assign
            }, 400)
        }
        function onEditSubmit() {
            editFormComponent.value.validate((valid) => {
                if (valid) {
                    editTask(editForm).then(() => {
                        fetchList()
                    }).finally(() => {
                        editVisible.value = false
                    })
                }
            })

        }

        function onNavTo(row) {
            console.log(row)
            router.push({
                name: "todo",
                query: {
                    taskId: row.id,
                },
            });
        }


        const startLoading = ref(false)
        function onStartTask(row) {
            startLoading.value = true
            startTask({
                taskId: row.id
            }).then(res => {
                fetchList()
            }).finally(() => {
                startLoading.value = false
            })
        }

        const pendingLoading = ref(false)
        function onPendingTask(row) {
            pendingLoading.value = true
            pendingTask({
                taskId: row.id
            }).then(res => {
                fetchList()
            }).finally(() => {
                pendingLoading.value = false
            })
        }

        const deleteLoading = ref(false)
        function onDeleteTask(row) {
            deleteLoading.value = true
            deleteTask({
                taskId: row.id
            }).then(res => {
                fetchList()
            }).finally(() => {
                deleteLoading.value = false
            })
        }

        const releaseLoading = ref(false)
        function onReleaseTask(row) {
            releaseForm.description = ''
        }

        function onReleaseTaskSubmit() {
            releaseLoading.value = true
            releaseTask({
                taskIdList: elTable.value.selection.map(item => item.id),
                description: releaseForm.description
            }).then(res => {
                releaseVisible.value = false
                fetchList()
            }).finally(() => {
                releaseLoading.value = false
            })
        }

        const releaseVisible = ref(false)
        const releaseForm = reactive({
            description: ''
        })


        function loadChildren(tree, treeNode, resolve) {
            getTaskList({
                orgId: props.orgId,
                ...searchForm,
                ...searchPageQuery,
                parentId: tree.id
            }).then((res) => {
                let data = res.data;

                data = data.list.map(item => ({
                    ...item,
                    workMillisecond: (item.workMillisecond / (1000 * 60 * 60)).toFixed(2),

                    // assignNicknameListStr: item.assignNicknameList.join(',')
                }))
                resolve(data)
                nextTick(() => {
                    nextTick(() => {
                        elTable.value.doLayout();
                    })
                })
            }).finally(() => {
            })
        }

        const pickerOptions = reactive({
            shortcuts: [
                {
                    text: '一小时前',
                    onClick(picker) {
                        picker.$emit('pick', [moment().subtract(1, 'hours').toDate(), moment().toDate()]);
                    }
                }
            ]
        })

        return {
            elTable,
            isSearchSelect,
            searchForm,
            searchPageQuery,
            searchTotal,
            priorityColor,
            taskTypeOptions,
            priorityOptions,
            releaseFlagOptions,
            responsiblePeopleOptions,
            tableData,
            fetchLoading,
            onSearch,
            onReset,
            onNavTo,
            createForm,
            createFormComponent,
            createVisible,
            onCreateSubmit,

            editVisible,
            editForm,
            editFormComponent,
            onEdit,
            onEditSubmit,

            onSortChange,

            startLoading,
            onStartTask,
            pendingLoading,
            onPendingTask,
            deleteLoading,
            onDeleteTask,
            releaseLoading,
            onReleaseTask,
            releaseForm,
            releaseVisible,
            onReleaseTaskSubmit,

            loadChildren,
            onCreateSub,
            rootFlagOptions,

            pickerOptions
        };
    },
})
</script>

<style scoped>
.t-link:hover {
    color: #409EFF;
    cursor: pointer;
}
</style>